﻿using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PublicMethod;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using WSBX.Models;

namespace OrderingOnlineWeChat.Controllers
{
    public class OrderController : BaseControl
    {
        #region 声明
        ZHHQService.Service1Client server1 = new ZHHQService.Service1Client();
        DCXTService.Service1Client server2 = new DCXTService.Service1Client();
        #endregion
        //
        // GET: /Order/
        #region View
        //下单页
        public ActionResult Index()
        {
            orderinfo info = (orderinfo)Session[SessionStorage.OrderInfo];
            ViewBag.totaMoney = info.totaMoney;
            return View();
        }
        //订单列表页
        public ActionResult OrderList()
        {
            Log.Debug("OrderList", "OrderList");
            return View();
        }
        //订单详细页
        public ActionResult OrderDetail()
        {
            return View();
        }
        //订单评价页
        public ActionResult Evaluate()
        {
            return View();
        }
        public ActionResult TiJiaoOrder()
        {
            Log.Debug("TiJiaoOrder", "进入提交");
            return View();
        }
        //再支付页
        public ActionResult RePayment()
        {
            return View();
        }
        #endregion

        JsApiPay jsApiPay = new JsApiPay();

        #region 计算订单总价
        public ActionResult getOrderTotal(string ID, int isTake)//Model.OrderTotal ordertotal
        {
            try
            {
                if (ID == null)
                {
                    ID = "";
                }
                orderinfo oinfo = (orderinfo)Session[SessionStorage.OrderInfo];//将Session保存的实体转成可直接使用的实体
                string[] DishIDs = oinfo.DishListArr;
                int[] DistCount = oinfo.CountArr;
                string MerID = oinfo.ShopInfo.MerID;
                string result = server2.CalcDiscount(DishIDs, DistCount, MerID, ID, isTake, GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);
                Model.OrderTotal shopinfo = obser<Model.OrderTotal>.DataContractJsonDeserialize(jb["rows"].ToString());//将json格式转为实体类
                //shopinfo.Discount = String.Format("{0:F}", Int32.Parse(shopinfo.Discount) * 0.01);
                shopinfo.Total = String.Format("{0:F}", Int32.Parse(shopinfo.Total) * 0.01);
                shopinfo.Discount = String.Format("{0:F}", Int32.Parse(shopinfo.Discount) * 0.01);
                var json = new
                {
                    shopinfo = oinfo.ShopInfo,
                    data = shopinfo
                };
                return Json(json);
            }
            catch (Exception) { return null; }

        }
        #endregion

        #region 订单提交
        public ActionResult BookOrder(bookorder bo, int isTake)//bookorder bo
        {
            Log.Debug("jinglaile ", "进来了");
            try
            {
                Model.Order_Form_T orderform = new Order_Form_T();
                orderinfo oinfo = (orderinfo)Session[SessionStorage.OrderInfo];//将Session保存的实体转成可直接使用的实体
                orderform.FormMerID = oinfo.ShopInfo.MerID;//商户ID
                orderform.OpenId = Session[SessionStorage.OpenID].ToString();

                #region 集合
                string FormDishesNun = "";
                string DishListArr = "";
                for (int i = 0; i < oinfo.CountArr.Length; i++)
                {
                    if (oinfo.CountArr[i] != 0)
                    {
                        FormDishesNun = FormDishesNun + oinfo.CountArr[i].ToString() + ","; //菜品数量集合
                        DishListArr = DishListArr + oinfo.DishListArr[i] + ",";//菜品ID集合
                    }
                }
                orderform.FormDishesID = DishListArr.Substring(0, DishListArr.Length - 1);//菜品ID集合
                orderform.FormDishesNun = FormDishesNun.Substring(0, FormDishesNun.Length - 1);//菜品数量集合
                //orderform.FormDishesID = string.Join(",", oinfo.DishListArr);//菜品ID集合
                //orderform.FormDishesNun = string.Join(",", oinfo.CountArr);//菜品数量集合
                #endregion

                #region 地址
                try
                {
                    Model.View_User dataresult = Session[SessionStorage.UserLogin] as Model.View_User;
                    orderform.AccID = dataresult.AccID;
                    orderform.AccName = bo.Contact.ContactName;
                    orderform.AccCall = bo.Contact.ContactCall;
                    orderform.FormAddress = bo.Contact.ContactAddress;
                }
                catch (Exception) { return Content("请选择送餐地址和支付方式！"); }
                #endregion

                #region 送餐时间、备注
                string date = "";
                string time = "";
                if (bo.Date == "今日")
                {
                    date = "0";
                }
                else
                {
                    date = bo.Date.Replace("-", "");
                }
                if (bo.Time.Length > 5)
                {
                    time = bo.Time.Substring(bo.Time.Length - 5, 5);
                    time = time.Replace(":", "") + "00";
                }
                else
                {
                    time = bo.Time.Replace(":", "") + "00";
                }
                if (date == "0" && time == "0")
                {
                    orderform.SenTime = "0";
                }
                else
                {
                    if (date == "0")
                    {
                        date = DateTime.Now.ToString("yyyyMMdd");
                    }
                    orderform.SenTime = date + time;
                }
                orderform.IntBZ = bo.BZ;
                orderform.Type = bo.Type;
                #endregion

                #region 钱包
                orderform.FormPayType = bo.Walt.PricType;//支付类型
                #endregion

                //string openid = Session[SessionStorage.OpenID].ToString();
                //string url = "http://paysdk.weixin.qq.com/example/JsApiPayPage.aspx?openid=" + openid + "&total_fee=100" ;
                //Response.Redirect(url);
                orderform.IsTake = isTake; // 1:派送 2：自取
                string json = orderform.ToJson();
                //Log.Debug("bo.Walt.ID", bo.Walt.ID);
                string result = server2.BookOrder(json, bo.Walt.ID, GetYZM._YZM, 1);
                Session["FormPayMon"] = bo.Total;//实际支付金额
                //Log.Debug("FormPayMon", bo.Total.ToString());
                JObject jb = JObject.Parse(result);

                //返回10，钱包支付
                //返回11，第三方支付
                if (jb["BS"].ToString() == "1")
                {
                    if (jb["rows"].ToString() != "")
                    {
                        Log.Debug("BookOrder", result);
                        //获取订单id
                        string[] aa = jb["rows"].ToString().Split('|');
                        Session[SessionStorage.FormID] = aa[0];

                        Session[SessionStorage.PayInfo] += "订单消费|" + jb["rows"].ToString();
                        Session[SessionStorage.OrderInfo] = null; // 购物车信息设置为null
                        if (jb["total"].ToString() == "1")
                        {
                            return Content("10");
                        }
                        else
                        {///微信支付
                            Log.Debug("jinglaile ", "进来了11111");
                            try
                            {
                                ServiceReference1.ServiceClient srconfig = new ServiceReference1.ServiceClient();
                                HttpContext httpcontext = System.Web.HttpContext.Current;
                                string urlCurrent = (!string.IsNullOrEmpty(httpcontext.Request.ServerVariables["HTTPS"])) && httpcontext.Request.ServerVariables["HTTPS"] != "off" ? "https://" : "http://";
                                urlCurrent += System.Web.HttpContext.Current.Request.Url.Host;
                                urlCurrent += httpcontext.Request.ServerVariables["URL"];
                                urlCurrent += string.IsNullOrEmpty(httpcontext.Request.ServerVariables["QUERY_STRING"]) ? "" : httpcontext.Request.ServerVariables["QUERY_STRING"];
                                Log.Debug("urlCurrent", urlCurrent);
                                string wxResult = srconfig.Query_WxYZMsg(urlCurrent, 1); //根据url从接口获取微信配置
                                string tonken = srconfig.GetAccess_token();
                                jb = JObject.Parse(wxResult);
                                WxResult wxRes = new WxResult();

                                wxRes.appId = jb["rows"]["appId"].ToString();
                                wxRes.nonceStr = jb["rows"]["nonceStr"].ToString();
                                wxRes.signature = jb["rows"]["signature"].ToString();
                                wxRes.timestamp = jb["rows"]["timestamp"].ToString();
                                ViewBag.wxRes = wxRes;

                                Session["appId"] = wxRes.appId;
                                Session["nonceStr"] = wxRes.nonceStr;
                                Session["signature"] = wxRes.signature;
                                Session["timestamp"] = wxRes.timestamp;

                                Session["token"] = tonken;
                                Log.Debug("token", tonken);



                            }
                            catch (Exception ex)
                            {
                                Log.Error("获取微信配置异常", ex.Message);
                            }

                            object objResult = "";
                            string strTotal_fee = bo.Total;
                            string strFee = (double.Parse(strTotal_fee) * 100).ToString();

                            //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数
                            Model.View_User dataresult = Session[SessionStorage.UserLogin] as Model.View_User;//将实体类保存至Session;
                            jsApiPay.openid = dataresult.AccMobile;
                            Log.Debug("total_fee", strFee);
                            jsApiPay.total_fee = int.Parse(strFee);

                            //JSAPI支付预处理
                            try
                            {
                                //string strBody = "筑波智慧";//商品描述
                                WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(aa[0]);
                                WxPayData wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数

                                ModelForOrder aOrder = new ModelForOrder()
                                {
                                    appId = wxJsApiParam.GetValue("appId").ToString(),
                                    nonceStr = wxJsApiParam.GetValue("nonceStr").ToString(),
                                    packageValue = wxJsApiParam.GetValue("package").ToString(),
                                    paySign = wxJsApiParam.GetValue("paySign").ToString(),
                                    timeStamp = wxJsApiParam.GetValue("timeStamp").ToString(),
                                    msg = "success"
                                };
                                objResult = aOrder;
                            }
                            catch (Exception ex)
                            {
                                ModelForOrder aOrder = new ModelForOrder()
                                {
                                    appId = "",
                                    nonceStr = "",
                                    packageValue = "",
                                    paySign = "",
                                    timeStamp = "",
                                    msg = "fail"
                                };
                                objResult = aOrder;
                            }

                            return Json(objResult);
                        }

                    }
                    return Content("10");
                }
                else
                {
                    return Content(jb["Msg"].ToString());
                }
            }
            catch (Exception)
            {
                return Content("error");
            }
        }

        public ActionResult BookOrder2(bookorder bo, int isTake)//bookorder bo
        {
            Log.Debug("确认下单", "进来了");
            try
            {
                Model.Order_Form_T orderform = new Order_Form_T();
                orderinfo oinfo = (orderinfo)Session[SessionStorage.OrderInfo];     //将Session保存的实体转成可直接使用的实体
                orderform.OpenId = Session[SessionStorage.OpenID].ToString();

                #region 集合
                Log.Debug("下单商品属性集合", "进来了");
                orderform.FormCarID = string.Join(",", oinfo.CarIDListArr);     //购物车ID集合
                orderform.FormDishesID = string.Join(",", oinfo.DishListArr);   //购物车商品ID集合
                orderform.FormDishesNun = string.Join(",", oinfo.CountArrs);    //购物车商品数量集合
                orderform.FormDisheName = string.Join(",", oinfo.DisheNameArr);       //商品名称集合
                orderform.FormDishesMon = string.Join(",", oinfo.DishesPayArr);       //商品价格集合
                orderform.DelFormMon = int.Parse((double.Parse(bo.DelFormMon) * 100).ToString());        //订单配送费
                orderform.DelPackMon = int.Parse((double.Parse(bo.DelPackMon) * 100).ToString());        //订单包装费用
                orderform.FormAllMon = int.Parse((double.Parse(bo.Total) * 100).ToString());       //订单合计总价
                orderform.FormPayMon = int.Parse((double.Parse(bo.Total) * 100).ToString());     //实际支付价格(暂无优惠等于合计总价)
                #endregion

                #region 地址
                try
                {
                    Log.Debug("下单配送地址", "进来了");
                    Model.View_User dataresult = Session[SessionStorage.UserLogin] as Model.View_User;
                    orderform.AccID = dataresult.AccID;
                    orderform.AccName = dataresult.AccName;
                    orderform.AccCall = dataresult.AccCall;
                    orderform.FormAddress = bo.SelectUserContact;
                }
                catch (Exception) { return Content("请选择送餐地址和支付方式！"); }
                #endregion

                #region 送餐时间、备注       
                Log.Debug("下单的送餐时间、备注", "进来了");
                string date = "";
                string time = "";
                if (bo.Date == "今日")
                {
                    date = "0";
                }
                else
                {
                    date = bo.Date.Replace("-", "");
                }
                if (bo.Time.Length > 5)
                {
                    time = bo.Time.Substring(bo.Time.Length - 5, 5);
                    time = time.Replace(":", "") + "00";
                }
                else
                {
                    time = bo.Time.Replace(":", "") + "00";
                }
                if (date == "0" && time == "0")
                {
                    orderform.SenTime = "0";
                }
                else
                {
                    if (date == "0")
                    {
                        date = DateTime.Now.ToString("yyyyMMdd");
                    }
                    orderform.SenTime = date + time;
                }
                orderform.IntBZ = bo.BZ;
                orderform.Type = bo.Type;       //下单类型（个人下单--200001，企业下单--200002）
                #endregion

                #region 钱包
                Log.Debug("下单的支付类型(微信支付)", "进来了");
                orderform.FormPayType = bo.WaltPricType;    //支付类型(微信支付)
                #endregion

                orderform.IsTake = isTake;  // 1:派送 2：自取
                string json = orderform.ToJson();
                string result = server2.BookOrder2(json, bo.WaltPayID, GetYZM._YZM, 1);
                Session["FormPayMon"] = bo.Total;   //实际支付金额
                JObject jb = JObject.Parse(result);
                //返回10，钱包支付
                //返回11，第三方支付
                if (jb["BS"].ToString() == "1")
                {
                    if (jb["rows"].ToString() != "")
                    {
                        Log.Debug("下单接口BookOrder2数据返回", result);
                        //获取订单id
                        string[] aa = jb["rows"].ToString().Split('|');
                        Session[SessionStorage.FormID] = aa[0];
                        Session[SessionStorage.PayInfo] += "订单消费|" + jb["rows"].ToString();
                        Session[SessionStorage.OrderInfo] = null;   // 购物车信息设置为null
                        if (jb["total"].ToString() == "1")
                        {
                            return Content("10");
                        }
                        else
                        {   //微信支付
                            Log.Debug("调起微信支付H5 ", "进来了");
                            try
                            {
                                ServiceReference1.ServiceClient srconfig = new ServiceReference1.ServiceClient();
                                HttpContext httpcontext = System.Web.HttpContext.Current;
                                string urlCurrent = (!string.IsNullOrEmpty(httpcontext.Request.ServerVariables["HTTPS"])) && httpcontext.Request.ServerVariables["HTTPS"] != "off" ? "https://" : "http://";
                                urlCurrent += System.Web.HttpContext.Current.Request.Url.Host;
                                urlCurrent += httpcontext.Request.ServerVariables["URL"];
                                urlCurrent += string.IsNullOrEmpty(httpcontext.Request.ServerVariables["QUERY_STRING"]) ? "" : httpcontext.Request.ServerVariables["QUERY_STRING"];
                                Log.Debug("urlCurrent", urlCurrent);
                                string wxResult = srconfig.Query_WxYZMsg(urlCurrent, 1); //根据url从接口获取微信配置
                                string tonken = srconfig.GetAccess_token();
                                jb = JObject.Parse(wxResult);
                                WxResult wxRes = new WxResult();

                                wxRes.appId = jb["rows"]["appId"].ToString();
                                wxRes.nonceStr = jb["rows"]["nonceStr"].ToString();
                                wxRes.signature = jb["rows"]["signature"].ToString();
                                wxRes.timestamp = jb["rows"]["timestamp"].ToString();
                                ViewBag.wxRes = wxRes;

                                Session["appId"] = wxRes.appId;
                                Session["nonceStr"] = wxRes.nonceStr;
                                Session["signature"] = wxRes.signature;
                                Session["timestamp"] = wxRes.timestamp;

                                Session["token"] = tonken;
                                Log.Debug("token", tonken);
                            }
                            catch (Exception ex)
                            {
                                Log.Error("获取微信配置异常", ex.Message);
                            }

                            object objResult = "";
                            string strTotal_fee = bo.Total;
                            string strFee = (double.Parse(strTotal_fee) * 100).ToString();

                            //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数
                            Model.View_User dataresult = Session[SessionStorage.UserLogin] as Model.View_User;//将实体类保存至Session;
                            jsApiPay.openid = dataresult.AccMobile;
                            Log.Debug("需要微信支付的价钱（实价乘以100）", strFee);
                            jsApiPay.total_fee = int.Parse(strFee);

                            //JSAPI支付预处理
                            try
                            {
                                //string strBody = "筑波智慧";//商品描述
                                WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(aa[0]);
                                WxPayData wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数

                                ModelForOrder aOrder = new ModelForOrder()
                                {
                                    appId = wxJsApiParam.GetValue("appId").ToString(),
                                    nonceStr = wxJsApiParam.GetValue("nonceStr").ToString(),
                                    packageValue = wxJsApiParam.GetValue("package").ToString(),
                                    paySign = wxJsApiParam.GetValue("paySign").ToString(),
                                    timeStamp = wxJsApiParam.GetValue("timeStamp").ToString(),
                                    msg = "success"
                                };
                                objResult = aOrder;
                            }
                            catch (Exception ex)
                            {
                                ModelForOrder aOrder = new ModelForOrder()
                                {
                                    appId = "",
                                    nonceStr = "",
                                    packageValue = "",
                                    paySign = "",
                                    timeStamp = "",
                                    msg = "fail"
                                };
                                objResult = aOrder;
                            }
                            return Json(objResult);
                        }
                    }
                    return Content("10");
                }
                else
                {
                    return Content(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Content("error" + ex.Message);
            }
        }
        #endregion

        #region 获取钱包、送餐时间、地址等信息
        /// <summary>
        /// 获取钱包信息
        /// </summary>
        /// <returns></returns>
        public ActionResult getBasicInfo()
        {
            try
            {
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int accid = int.Parse(userinfoModel.AccID.ToString());

                #region 支付方式
                orderinfo oinfo = (orderinfo)Session[SessionStorage.OrderInfo];//将Session保存的实体转成可直接使用的实体
                string merid = oinfo.ShopInfo.MerID;
                string walt = server2.GetUserPayWalt(accid, merid, GetYZM._YZM, 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(walt, 1);
                List<aa> ls = new List<aa>();

                JObject jb = JObject.Parse(walt);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<aa>.JsonList(jieguo);
                for (int i = 0; i < ls.Count; i++)
                {
                    ls[i].bb = "2";
                    if (String.Equals(ls[i].PriTxt, "")) { ls[i].PriTxt = "无优惠"; }
                }
                #endregion

                #region 地址
                string result = server2.GetUserContactByMerid(merid, accid, GetYZM._YZM, 1);
                Model.DataResult dr1 = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                //tal = dr.total.ToString();
                List<Model.User_Contact_T> ls1 = new List<Model.User_Contact_T>();
                JObject jb1 = JObject.Parse(result);
                IList<JToken> jieguo1 = jb1["rows"].Children().ToList();
                ls1 = ParseClass<Model.User_Contact_T>.JsonList(jieguo1);
                #endregion

                #region 获取送餐时间
                string datetime = server2.GetOrderTime(merid, GetYZM._YZM, 1);
                JObject dt = JObject.Parse(datetime);
                IList<JToken> jieguo2 = dt["rows"].Children().ToList();
                Model.OrderTotal openinfo = obser<Model.OrderTotal>.DataContractJsonDeserialize(dt["rows"].ToString());//将json格式转为实体类
                if (openinfo.DeliveryTime.Count > 0)
                {
                    openinfo.DeliveryTime[0] = "最快送达" + openinfo.DeliveryTime[0];
                }
                if (openinfo.DeliveryDate.Count == 0)
                {
                    string today = DateTime.Now.ToString("yyyy-MM-dd");
                    openinfo.DeliveryDate.Add(today);
                }
                #endregion

                var data = new
                {
                    //total = ls.Count,
                    walt = ls,
                    address = ls1,
                    opentiem = openinfo.DeliveryTime,
                    opendate = openinfo.DeliveryDate
                };
                return Json(data);
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 根据商户id获取该商户所有派送范围
        /// <summary>
        /// 根据商户id获取该商户所有派送范围
        /// </summary>
        /// <returns></returns>
        public ActionResult getallsendfrommerid()
        {
            try
            {
                orderinfo oinfo = (orderinfo)Session[SessionStorage.OrderInfo];//将Session保存的实体转成可直接使用的实体
                string merid = oinfo.ShopInfo.MerID;

                string address = server2.GetSendAddFromMerId(1, 1000, merid, GetYZM._YZM, 1);
                Log.Debug("获取商户范围地址", "merid" + merid + "  |" + address);
                List<Model.View_Order_MerSend> ls = new List<Model.View_Order_MerSend>();
                JObject jb = JObject.Parse(address);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<Model.View_Order_MerSend>.JsonList(jieguo);
                var data = new
                {
                    list = ls
                };
                return Json(data);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

        #region 获取所有订单列表
        public ActionResult getOrderList(string Type, int pageIndex, int pageSize)
        {
            try
            {
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int acc = int.Parse(userinfoModel.AccID.ToString());
                //int acc = 39;
                string result = server2.GetOrder_Form_User(pageIndex, pageSize, Session[SessionStorage.OpenID].ToString(), 0, GetYZM._YZM, 1);
                List<Model.View_Order_Form> ls = new List<Model.View_Order_Form>();
                JObject jb = JObject.Parse(result);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<Model.View_Order_Form>.JsonList(jieguo);
                List<allorderlist> ols = new List<allorderlist>();

                //string aa = Session[SessionStorage.OrderList].ToString();
                //if (aa != "")
                //{
                //    ols = (List<allorderlist>)Session[SessionStorage.OrderList];
                //}

                for (int i = 0; i < ls.Count; i++)
                {
                    ls[i].FormTime = DateTimeHelper.ToDate2(ls[i].FormTime);
                    if (ls[i].SenTime == "0")
                    {
                        ls[i].SenTime = "立即送餐";
                    }
                    else
                    {
                        ls[i].SenTime = DateTimeHelper.ToDate2(ls[i].SenTime);//当送餐时间为立即送餐时未处理
                    }
                    allorderlist ol = new allorderlist();
                    ol.FormAllMon = String.Format("{0:F}", ls[i].FormAllMon * 0.01);
                    ol.vof = ls[i];
                    ol.FormDisheID = ls[i].FormDishesID.Split(',');
                    ol.FormDisheName = ls[i].FormDisheName.Split(',');
                    ol.FormDishesNun = ls[i].FormDishesNun.Split(',');
                    ol.FormDishesMon = ls[i].FormDishesMon.Split(',');
                    if (Type == "0")
                    {
                        ol.FornDishesInt = ls[i].FornDishesInt.Split(',');//积分
                    }
                    var sub = ls[i].FormBY.Substring(1, 1);
                    if (sub == "A")
                    {
                        var a = ls[i].FormBY.Substring(3, 1);
                        if (a == "1")
                        {
                            ol.FormBY = "等待订单";
                        }
                        else if (a == "2")
                        {
                            ol.FormBY = "提交订单";
                        }
                        else if (a == "3")
                        {
                            ol.FormBY = "商户确认订单";
                        }
                        else if (a == "4")
                        {
                            ol.FormBY = "通知派送";
                        }
                        else if (a == "5")
                        {
                            ol.FormBY = "订单完成";
                        }
                        else if (a == "6")
                        {
                            ol.FormBY = "订单关闭";
                        }
                    }
                    else if (sub == "B")
                    {
                        var a = ls[i].FormBY.Substring(3, 1);
                        if (a == "1")
                        {
                            ol.FormBY = "通知送餐员";
                        }
                        else if (a == "2")
                        {
                            ol.FormBY = "送餐员正赶往餐厅";
                        }
                        else if (a == "3")
                        {
                            ol.FormBY = "送餐员已取货";
                        }
                        else if (a == "4")
                        {
                            ol.FormBY = "派送完成";
                        }
                        else if (a == "5")
                        {
                            ol.FormBY = "派送停止";
                        }
                    }

                    ols.Add(ol);
                }

                Session[SessionStorage.OrderList] = ols;

                var data = new
                {
                    total = jb["total"].ToString(),
                    rows = ols
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex) { return null; }
        }

        public ActionResult getOrderList2(string Type, int pageIndex, int pageSize)
        {
            try
            {
                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int acc = int.Parse(userinfoModel.AccID.ToString());
                //int acc = 39;
                string result = server2.GetOrder_Form_User(pageIndex, pageSize, Session[SessionStorage.OpenID].ToString(), 0, GetYZM._YZM, 1);
                List<Model.View_Order_Form> ls = new List<Model.View_Order_Form>();
                JObject jb = JObject.Parse(result);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<Model.View_Order_Form>.JsonList(jieguo);
                List<allorderlist> ols = new List<allorderlist>();

                //string aa = Session[SessionStorage.OrderList].ToString();
                //if (aa != "")
                //{
                //    ols = (List<allorderlist>)Session[SessionStorage.OrderList];
                //}

                for (int i = 0; i < ls.Count; i++)
                {
                    ls[i].FormTime = DateTimeHelper.ToDate2(ls[i].FormTime);
                    if (ls[i].SenTime == "0")
                    {
                        ls[i].SenTime = "立即送餐";
                    }
                    else
                    {
                        ls[i].SenTime = DateTimeHelper.ToDate2(ls[i].SenTime);//当送餐时间为立即送餐时未处理
                    }
                    allorderlist ol = new allorderlist();
                    ol.FormAllMon = String.Format("{0:F}", ls[i].FormAllMon * 0.01);
                    //ol.FormAllMon = String.Format("{0:F}", ls[i].FormAllMon);
                    ol.vof = ls[i];
                    ol.FormDisheID = ls[i].FormDishesID.Split(',');
                    ol.FormDisheName = ls[i].FormDisheName.Split(',');
                    ol.FormDishesNun = ls[i].FormDishesNun.Split(',');
                    ol.FormDishesMon = ls[i].FormDishesMon.Split(',');
                    if (Type == "0")
                    {
                        if (ls[i].FornDishesInt != "" && ls[i].FornDishesInt != null)
                        {
                            ol.FornDishesInt = ls[i].FornDishesInt.Split(',');//积分
                        }
                    }
                    var sub = ls[i].FormBY.Substring(1, 1);
                    if (sub == "A")
                    {
                        var a = ls[i].FormBY.Substring(3, 1);
                        if (a == "1")
                        {
                            ol.FormBY = "等待订单";
                        }
                        else if (a == "2")
                        {
                            ol.FormBY = "提交订单";
                        }
                        else if (a == "3")
                        {
                            ol.FormBY = "商户确认订单";
                        }
                        else if (a == "4")
                        {
                            ol.FormBY = "通知派送";
                        }
                        else if (a == "5")
                        {
                            ol.FormBY = "订单完成";
                        }
                        else if (a == "6")
                        {
                            ol.FormBY = "订单关闭";
                        }
                    }
                    else if (sub == "B")
                    {
                        var a = ls[i].FormBY.Substring(3, 1);
                        if (a == "1")
                        {
                            ol.FormBY = "通知送餐员";
                        }
                        else if (a == "2")
                        {
                            ol.FormBY = "送餐员正赶往餐厅";
                        }
                        else if (a == "3")
                        {
                            ol.FormBY = "送餐员已取货";
                        }
                        else if (a == "4")
                        {
                            ol.FormBY = "派送完成";
                        }
                        else if (a == "5")
                        {
                            ol.FormBY = "派送停止";
                        }
                    }

                    ols.Add(ol);
                }

                Session[SessionStorage.OrderList] = ols;

                var data = new
                {
                    total = jb["total"].ToString(),
                    rows = ols
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex) { return null; }
        }
        #endregion

        public ActionResult tjjs()
        {
            Log.Debug("tjjs", "进入提交");
            int fmid = int.Parse(Session[SessionStorage.FormID].ToString());
            string result = server2.updFormBY(fmid, "", GetYZM._YZM, 1);
            JObject jb = JObject.Parse(result);
            //返回10，钱包支付
            //返回11，第三方支付
            return Content("1");

        }
        public void addOrderList(allorderlist ol)
        {

        }

        #region 根据订单ID获取订单信息
        /// <summary>
        /// 根据订单ID获取订单信息
        /// </summary>
        /// <param name="orderNum"></param>
        /// <returns></returns>
        public ActionResult getDetail(int orderNum)
        {
            try
            {
                string result = server2.getOrderDetailByOrderID(orderNum, GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);
                View_Order_Form vof = new View_Order_Form();
                allorderlist ol = new allorderlist();
                if (jb["BS"].ToString() == "1")
                {
                    vof = obser<Model.View_Order_Form>.DataContractJsonDeserialize(jb["rows"].ToString());//将json格式转为实体类
                    ol.FormAllMon = vof.FormAllMon.ToString();
                    ol.vof = vof;
                    ol.vof.FormTime = DateTimeHelper.ToDate2(vof.FormTime);
                    ol.vof.LastTime = DateTimeHelper.ToDate2(vof.LastTime);
                    ol.vof.SenTime = DateTimeHelper.ToDate2(vof.SenTime);

                    ol.FormDisheID = vof.FormDishesID.Split(',');
                    ol.FormDisheName = vof.FormDisheName.Split(',');
                    ol.FormDishesNun = vof.FormDishesNun.Split(',');
                    ol.FormDishesMon = vof.FormDishesMon.Split(',');
                    //if (Type == "0")
                    //{
                    if (vof.FornDishesInt != "" && vof.FornDishesInt != null)
                    {
                        ol.FornDishesInt = vof.FornDishesInt.Split(',');//积分
                    }
                    //}
                }
                //List<allorderlist> ols = (List<allorderlist>)Session[SessionStorage.OrderList];
                //allorderlist ol = new allorderlist();
                //foreach (allorderlist item in ols)
                //{
                //    if (item.vof.FormID == orderNum)
                //    {
                //        ol = item;
                //    }
                //}
                //var data = new { info = ol };
                return Json(ol);
            }
            catch (Exception ex) { return Content(ex.ToString()); }
        }
        #endregion

        #region 添加商品评价信息
        /// <summary>
        /// 添加商品评价信息
        /// </summary>
        /// <param name="FormID"></param>
        /// <param name="EvaTxt"></param>
        /// <param name="EvaStars"></param>
        /// <param name="GoodDishes"></param>
        /// <returns></returns>
        public ActionResult addOrderEva(string FormID, string EvaTxt, int EvaStars, string[] GoodDishes)
        {
            try
            {
                string result = server2.AddOrderEva(FormID, GoodDishes, EvaTxt, EvaStars, GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);
                string bs = jb["BS"].ToString();
                if (bs == "1")
                {
                    return Content("OK");
                }
                else
                {
                    return Content(jb["Msg"].ToString());
                }
            }
            catch (Exception) { return null; }
        }
        #endregion

        #region 查询订单是否付款成功
        public ActionResult FormIsPay()
        {
            try
            {
                int formID = int.Parse(Session[SessionStorage.FormID].ToString());
                string result = server2.FeatchIspy(formID, GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);
                return Content(jb["BS"].ToString());
            }
            catch (Exception ex) { return Content(ex.ToString()); }
        }
        #endregion

        #region 获取系统设置信息
        /// <summary>
        /// 获取系统设置信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOrder_Key()
        {
            try
            {
                string result = server2.GetOrder_Key(GetYZM._YZM, 1);
                List<Model.Order_Key_T> List_Info = new List<Order_Key_T>();
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                //bs.Substring(0,1)
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        List_Info = ParseClass<Model.Order_Key_T>.JsonList(jieguo);//解析返回的结果
                    }

                    return Json(List_Info, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception)
            {
                return null;
            }

        }
        #endregion

        #region 选择支付方式继续支付
        /// <summary>
        /// 选择支付方式继续支付
        /// </summary>
        /// <param name="FormID">旧订单号</param>
        /// <param name="PayID">新的支付ID</param>
        /// <param name="lx">1:计算新优惠  2：变更原有优惠 3：删除该订单</param>
        /// <returns></returns>
        public ActionResult ReBookOrder(int FormID, string PayID, int lx, int isTake)  ///lz
        {

            try
            {
                string result = server2.ReBookOrder2(FormID, PayID, lx, isTake, GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() != "1")
                {
                    var json = new
                    {
                        bs = jb["BS"].ToString(),
                        mes = jb["Msg"].ToString(),
                    };
                    return Json(json);
                }
                else
                {
                    Model.OrderTotal shopinfo = obser<Model.OrderTotal>.DataContractJsonDeserialize(jb["rows"].ToString());//将json格式转为实体类

                    var json = new
                    {
                        bs = jb["BS"].ToString(),
                        data = shopinfo,
                        mes = jb["Msg"].ToString(),
                    };
                    return Json(json);
                }
            }
            catch (Exception)
            { return null; }
        }
        #endregion

        #region 删除订单
        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="FormID">旧订单号</param>
        /// <param name="PayID">新的支付ID</param>
        /// <param name="lx">1:计算新优惠  2：变更原有优惠 3：删除该订单</param>
        /// <returns></returns>
        public ActionResult DeleteBookOrder(int FormID, string PayID, int lx, int isTake)  ///lz
        {

            try
            {
                string result = server2.ReBookOrder2(FormID, PayID, lx, isTake, GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);

                //Model.OrderTotal shopinfo = obser<Model.OrderTotal>.DataContractJsonDeserialize(jb["rows"].ToString());//将json格式转为实体类

                var json = new
                {
                    bs = jb["BS"].ToString(),
                    mes = jb["Msg"].ToString(),
                };
                return Json(json);

            }
            catch (Exception)
            { return null; }
        }
        #endregion

        #region 修改订单支付方式
        /// <summary>
        /// 修改订单支付方式
        /// </summary>
        /// <param name="FormID">旧订单号</param>
        /// <param name="PayID">新的支付ID</param>
        /// <param name="lx">1:计算新优惠  2：变更原有优惠 3：删除该订单</param>
        /// <returns></returns>
        public ActionResult PayBookOrder(int FormID, string PayID, int lx, int isTake)
        {
            try
            {
                string result = server2.ReBookOrder2(FormID, PayID, lx, isTake, GetYZM._YZM, 1);
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() != "1")
                {
                    var json = new
                    {
                        bs = jb["BS"].ToString(),
                        mes = jb["Msg"].ToString(),
                    };
                    return Json(json);
                }
                else
                {
                    if (jb["rows"].ToString() != "")
                    {
                        //获取订单id
                        string[] aa = jb["rows"].ToString().Split('|');
                        Session[SessionStorage.FormID] = aa[0];

                        Session[SessionStorage.PayInfo] += "订单消费|" + jb["rows"].ToString();
                        Session[SessionStorage.OrderInfo] = null; // 购物车信息设置为null
                        if (jb["total"].ToString() == "1")
                        {
                            return Content("10");
                        }

                        ///微信支付
                        Log.Debug("继续支付（微信）", "继续支付（微信）进来了11111");
                        try
                        {
                            ServiceReference1.ServiceClient srconfig = new ServiceReference1.ServiceClient();
                            HttpContext httpcontext = System.Web.HttpContext.Current;
                            string urlCurrent = (!string.IsNullOrEmpty(httpcontext.Request.ServerVariables["HTTPS"])) && httpcontext.Request.ServerVariables["HTTPS"] != "off" ? "https://" : "http://";
                            urlCurrent += System.Web.HttpContext.Current.Request.Url.Host;
                            urlCurrent += httpcontext.Request.ServerVariables["URL"];
                            urlCurrent += string.IsNullOrEmpty(httpcontext.Request.ServerVariables["QUERY_STRING"]) ? "" : httpcontext.Request.ServerVariables["QUERY_STRING"];
                            Log.Debug("urlCurrent", urlCurrent);
                            string wxResult = srconfig.Query_WxYZMsg(urlCurrent, 1); //根据url从接口获取微信配置
                            string tonken = srconfig.GetAccess_token();
                            jb = JObject.Parse(wxResult);
                            WxResult wxRes = new WxResult();

                            wxRes.appId = jb["rows"]["appId"].ToString();
                            wxRes.nonceStr = jb["rows"]["nonceStr"].ToString();
                            wxRes.signature = jb["rows"]["signature"].ToString();
                            wxRes.timestamp = jb["rows"]["timestamp"].ToString();
                            ViewBag.wxRes = wxRes;

                            Session["appId"] = wxRes.appId;
                            Session["nonceStr"] = wxRes.nonceStr;
                            Session["signature"] = wxRes.signature;
                            Session["timestamp"] = wxRes.timestamp;

                            Session["token"] = tonken;
                            Log.Debug("token", tonken);
                        }
                        catch (Exception ex)
                        {
                            Log.Error("获取微信配置异常", ex.Message);
                        }

                        object objResult = "";
                        string strTotal_fee = aa[1];
                        string strFee = (double.Parse(strTotal_fee)).ToString();

                        //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数
                        Model.View_User dataresult = Session[SessionStorage.UserLogin] as Model.View_User;//将实体类保存至Session;
                        jsApiPay.openid = dataresult.AccMobile;
                        Log.Debug("total_fee", strFee);
                        jsApiPay.total_fee = int.Parse(strFee);

                        //JSAPI支付预处理
                        try
                        {
                            //string strBody = "筑波智慧";//商品描述
                            WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(aa[0]);
                            WxPayData wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数

                            ModelForOrder aOrder = new ModelForOrder()
                            {
                                appId = wxJsApiParam.GetValue("appId").ToString(),
                                nonceStr = wxJsApiParam.GetValue("nonceStr").ToString(),
                                packageValue = wxJsApiParam.GetValue("package").ToString(),
                                paySign = wxJsApiParam.GetValue("paySign").ToString(),
                                timeStamp = wxJsApiParam.GetValue("timeStamp").ToString(),
                                msg = "success"
                            };
                            objResult = aOrder;
                        }
                        catch (Exception ex)
                        {
                            ModelForOrder aOrder = new ModelForOrder()
                            {
                                appId = "",
                                nonceStr = "",
                                packageValue = "",
                                paySign = "",
                                timeStamp = "",
                                msg = "fail"
                            };
                            objResult = aOrder;
                        }

                        return Json(objResult);
                        //return Content("11");
                    }
                    var json = new
                    {
                        bs = jb["BS"].ToString(),
                        mes = jb["Msg"].ToString(),
                    };
                    return Json(json);
                }
            }
            catch (Exception ex)
            {
                var json = new
                {
                    bs = "-99",
                    mes = "系统内部异常#33" + ex,
                };
                return Json(json);
            }
        }
        #endregion

        #region 获取指定商户的可使用钱包信息
        /// <summary>
        /// 获取指定商户的可使用钱包信息
        /// </summary>
        /// <returns></returns>
        public ActionResult getBasicInfoByMerID(string MerID)
        {
            try
            {

                Model.View_User userinfoModel = (Model.View_User)Session[SessionStorage.UserLogin];//将Session保存的实体转成可直接使用的实体
                int accid = int.Parse(userinfoModel.AccID.ToString());

                #region 支付方式
                string walt = server2.GetUserPayWalt(accid, MerID, GetYZM._YZM, 1);
                // Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(walt, 1);
                List<aa> ls = new List<aa>();
                JObject jb = JObject.Parse(walt);
                IList<JToken> jieguo = jb["rows"].Children().ToList();
                ls = ParseClass<aa>.JsonList(jieguo);
                foreach (aa c in ls)
                {
                    c.bb = "2";
                }
                #endregion

                var data = new
                {
                    //total = ls.Count,
                    walt = ls,
                };
                return Json(data);
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        //新的获取地址列表接口
        public ActionResult GetUserSendAddr(string MerId)
        {
            string openid = Session[SessionStorage.OpenID].ToString();
            string result = server2.GetUserSendAddr(openid, MerId, "", 1);
            return Content(result);
        }


        public class aa
        {
            public string ID { get; set; }
            public string Name { get; set; }
            public int PricType { get; set; }
            public string PriTxt { get; set; }

            public string bb { get; set; }
        }


        public class ModelForOrder
        {
            public string appId { get; set; }
            public string timeStamp { get; set; }
            public string nonceStr { get; set; }
            public string packageValue { get; set; }
            public string paySign { get; set; }

            public string msg { get; set; }
        }

        public class JsApiPay
        {
            /// <summary>
            /// 保存页面对象，因为要在类的方法中使用Page的Request对象
            /// </summary>
            private Page page { get; set; }

            /// <summary>
            /// openid用于调用统一下单接口
            /// </summary>
            public string openid { get; set; }

            /// <summary>
            /// access_token用于获取收货地址js函数入口参数
            /// </summary>
            public string access_token { get; set; }

            /// <summary>
            /// 商品金额，用于统一下单
            /// </summary>
            public int total_fee { get; set; }

            /// <summary>
            /// 统一下单接口返回结果
            /// </summary>
            public WxPayData unifiedOrderResult { get; set; }

            public JsApiPay()
            {

            }

            /**
             * 调用统一下单，获得下单结果
             * @return 统一下单结果
             * @失败时抛异常WxPayException
             */
            public WxPayData GetUnifiedOrderResult(string strBody)
            {
                //统一下单
                WxPayData data = new WxPayData();
                data.SetValue("body", strBody);
                data.SetValue("attach", strBody);
                Log.Debug("统一下单1610", strBody);
                //data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
                data.SetValue("out_trade_no", strBody);
                data.SetValue("total_fee", total_fee);
                data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
                data.SetValue("goods_tag", "test");
                data.SetValue("trade_type", "JSAPI");
                data.SetValue("openid", openid);
                data.SetValue("sub_openid", openid);
                WxPayData result = WxPayApi.UnifiedOrder(data);
                if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
                {
                    Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                    throw new WxPayException("UnifiedOrder response error!");
                }

                unifiedOrderResult = result;
                return result;
            }

            /**
            *  
            * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数，
            * 微信浏览器调起JSAPI时的输入参数格式如下：
            * {
            *   "appId" : "wx2421b1c4370ec43b",     //公众号名称，由商户传入     
            *   "timeStamp":" 1395712654",         //时间戳，自1970年以来的秒数     
            *   "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串     
            *   "package" : "prepay_id=u802345jgfjsdfgsdg888",     
            *   "signType" : "MD5",         //微信签名方式:    
            *   "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
            * }
            * @return string 微信浏览器调起JSAPI时的输入参数，json格式可以直接做参数用
            * 更详细的说明请参考网页端调起支付API：http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
            * 
            */
            public WxPayData GetJsApiParameters()
            {

                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("appId", WxPayConfig.APPID);
                jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
                jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
                Log.Debug("prepay_id", unifiedOrderResult.GetValue("prepay_id").ToString());
                jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                jsApiParam.SetValue("signType", "MD5");
                jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

                string parameters = jsApiParam.ToJson();
                Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
                return jsApiParam;
            }
            //public string GetJsApiParameter()
            //{
            //    Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");

            //    WxPayData jsApiParam = new WxPayData();
            //    jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
            //    jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            //    jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            //    jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
            //    jsApiParam.SetValue("signType", "MD5");
            //    jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

            //    string parameters = jsApiParam.ToJson();
            //    Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            //    return parameters;
            //}


            /**
            * 
            * 获取收货地址js函数入口参数,详情请参考收货地址共享接口：http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_9
            * @return string 共享收货地址js函数需要的参数，json格式可以直接做参数使用
            */
            public string GetEditAddressParameters()
            {
                string parameter = "";
                try
                {
                    string host = page.Request.Url.Host;
                    string path = page.Request.Path;
                    string queryString = page.Request.Url.Query;
                    //这个地方要注意，参与签名的是网页授权获取用户信息时微信后台回传的完整url
                    string url = "http://" + host + path + queryString;

                    //构造需要用SHA1算法加密的数据
                    WxPayData signData = new WxPayData();
                    signData.SetValue("appid", WxPayConfig.APPID);
                    signData.SetValue("url", url);
                    signData.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
                    signData.SetValue("noncestr", WxPayApi.GenerateNonceStr());
                    signData.SetValue("accesstoken", access_token);
                    string param = signData.ToUrl();

                    Log.Debug(this.GetType().ToString(), "SHA1 encrypt param : " + param);
                    //SHA1加密
                    string addrSign = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1");
                    Log.Debug(this.GetType().ToString(), "SHA1 encrypt result : " + addrSign);

                    //获取收货地址js函数入口参数
                    WxPayData afterData = new WxPayData();
                    afterData.SetValue("appId", WxPayConfig.APPID);
                    afterData.SetValue("scope", "jsapi_address");
                    afterData.SetValue("signType", "sha1");
                    afterData.SetValue("addrSign", addrSign);
                    afterData.SetValue("timeStamp", signData.GetValue("timestamp"));
                    afterData.SetValue("nonceStr", signData.GetValue("noncestr"));

                    //转为json格式
                    parameter = afterData.ToJson();
                    Log.Debug(this.GetType().ToString(), "Get EditAddressParam : " + parameter);
                }
                catch (Exception ex)
                {
                    Log.Error(this.GetType().ToString(), ex.ToString());
                    throw new WxPayException(ex.ToString());
                }

                return parameter;
            }
        }


        #region 确认订单页面获取信息
        /// <summary>
        /// 获取购物车选中的商品
        /// </summary>
        /// <param name="CarID">购物车商品ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public ActionResult GetDishesShoppingCar(string[] CarID, string YZM, int RETID)
        {
            try
            {
                orderinfo oinfo = (orderinfo)Session[SessionStorage.OrderInfo];
                CarID = oinfo.CarIDListArr;
                string result = server2.GetDishesShoppingCar(CarID, YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 获取登陆用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUserinfo()
        {
            try
            {
                View_User userinfoModel = (View_User)Session[SessionStorage.UserLogin];
                if (userinfoModel != null)
                {
                    return Json(userinfoModel);
                }
                else { return null; }
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 查询用户的地址
        /// </summary>
        /// <param name="OpenId">微信ID</param>
        /// <param name="AccID">用户ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public ActionResult GetAllUserSendAddr(string OpenId, int AccID, string YZM, int RETID)
        {
            try
            {
                View_User userinfoModel = (View_User)Session[SessionStorage.UserLogin];
                if (userinfoModel != null)
                {
                    AccID = userinfoModel.AccID;
                }
                string userJson = JsonConvert.SerializeObject(Session[SessionStorage.OpenID]).ToString();
                if (userJson != "")
                {
                    OpenId = userJson.Replace("\"", "");
                }
                string result = server2.GetAllUserSendAddr(OpenId, AccID, YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 根据用户选择的地址获取配送费
        /// </summary>
        /// <param name="DistrictID">区域ID</param>
        /// <returns></returns>
        public ActionResult GetUserDistrict(string DistrictID)
        {
            try
            {
                string result = server2.Get_User_DistrictsByDistrictID(DistrictID, "", 1);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        #endregion

        #region 用户付款成功后更新订单支付状态
        public ActionResult UpdateFormIsPay()
        {
            try
            {
                int formID = int.Parse(Session[SessionStorage.FormID].ToString());
                string result = server2.UpdateFormIsPay(formID, GetYZM._YZM, 1);
                return Content(result);
            }
            catch (Exception ex) { return Content(ex.ToString()); }
        }
        #endregion
    }
}
